import { useState, useEffect, useContext } from 'react';
import { NavBar, Popup, Tabs, List, Image, InfiniteScroll  } from 'antd-mobile';
import { MySdkStoreContext } from '../../context';
import AvatarImage from '../AvatarImage'

interface PropsType {
  cid: string;
  messageId: string;
  onClose: () => void;
}

export default function(props: PropsType) {
  const { onClose } = props;
  const mySdkStore = useContext(MySdkStoreContext);
  const { cid, messageId } = props;
  const [list, setList] = useState([]);
  const [pagination, setPagination] = useState({});
  const [tabKey, setTabKey] = useState(0);
  // 已读/未读人数统计
  const [countNumber, setCountNumber] = useState({});

  // 获取已读/未读人员列表
  const getList = async (pageIndex, status = tabKey) => {
    const data = await mySdkStore.sdk.queryMessageReadOrUnReadUsers({ cid, messageId, status, pageIndex });
    const { rows = [], next, current, totalItemCount, totalPage } = data;
    setList(pageIndex === 1 ? rows : [...list, ...rows]);
    setPagination({ pageIndex: current, next: +next, totalItemCount, totalPage });
  }

  useEffect(() => {
    getList(1);
  }, []);

  // 获取已读/未读人数统计
  useEffect(async () => {
    const data = await mySdkStore.sdk.queryMessageReadOrUnReadStatus({ cid, messageId });
    setCountNumber(data);
  }, []);

  const handleChange = (key) => {
    setTabKey(key);
    getList(1, +key);
  }

  const renderList = () => {
    return <><List style={{ '--border-inner': 0 }}>
      {list.map(item => {
        return <List.Item
          key={item.userId}
          prefix={
          <>
            <AvatarImage
              src={item.avatarUrl}
              style={{ display: 'inline-block', borderRadius: 8 }}
              fit='cover'
              width={36}
              height={36}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
            />
        </>}>{item.nickName || item.userName || item.useId}</List.Item>
      })}
    </List>
    <InfiniteScroll loadMore={() => getList(pagination.pageIndex + 1)} hasMore={pagination.totalPage > pagination.pageIndex} />
    </>
  }

  return <Popup
    visible
    bodyStyle={{ height: '90%', overflow: 'scroll' }}
  >
    <NavBar onBack={() => onClose()} style={{ background: '#fff', border: 'none' }}>消息接受人列表</NavBar>
    <Tabs onChange={handleChange} className="pageTab">
      <Tabs.Tab title={`未读(${countNumber.unReadUserCount})`} key={0}>
        {renderList()}
      </Tabs.Tab>
      <Tabs.Tab title={`已读(${countNumber.readUserCount})`} key={1}>
        {renderList()}
      </Tabs.Tab>
    </Tabs>
  </Popup>
}